package com.example.javaproject.controller;

import com.example.javaproject.common.R;
import com.example.javaproject.entity.PositionApplication;
import com.example.javaproject.service.PositionApplicationService;
import com.example.javaproject.service.StudentService;
import com.example.javaproject.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/application")
public class PositionApplicationController {
    @Autowired
    private PositionApplicationService positionApplicationService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @PostMapping("/apply")
    public R apply(@RequestBody PositionApplication application, @RequestHeader("Authorization") String token) {
        // 解析token获取userId
        String realToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Integer userId = null;
        try {
            io.jsonwebtoken.Claims claims = com.example.javaproject.util.JwtUtil.parseToken(realToken);
            Object idObj = claims.get("userId");
            if (idObj instanceof Integer) {
                userId = (Integer) idObj;
            } else if (idObj instanceof Number) {
                userId = ((Number) idObj).intValue();
            } else if (idObj != null) {
                userId = Integer.parseInt(idObj.toString());
            }
        } catch (Exception e) {
            return R.error("token无效或已过期");
        }
        if (userId == null) {
            return R.error("未登录或token无效");
        }
        // 通过 userId 查 studentId
        com.example.javaproject.entity.Student student = studentService.getByUserId(userId);
        if (student == null) {
            return R.error("未找到对应学生信息");
        }
        application.setStudentId(student.getId());
        boolean success = positionApplicationService.applyPosition(application);
        if (success) {
            return R.ok(null);
        } else {
            return R.error("申请失败");
        }
    }

    @GetMapping("/my-applications")
    public R getMyApplications(@RequestHeader("Authorization") String token,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "8") Integer size,
                               @RequestParam(required = false) String positionName,
                               @RequestParam(required = false) Integer status) {
        // 解析token获取userId
        String realToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Integer userId = null;
        try {
            io.jsonwebtoken.Claims claims = com.example.javaproject.util.JwtUtil.parseToken(realToken);
            Object idObj = claims.get("userId");
            if (idObj instanceof Integer) {
                userId = (Integer) idObj;
            } else if (idObj instanceof Number) {
                userId = ((Number) idObj).intValue();
            } else if (idObj != null) {
                userId = Integer.parseInt(idObj.toString());
            }
        } catch (Exception e) {
            return R.error("token无效或已过期");
        }
        if (userId == null) {
            return R.error("未登录或token无效");
        }
        
        // 通过 userId 查 studentId
        com.example.javaproject.entity.Student student = studentService.getByUserId(userId);
        if (student == null) {
            return R.error("未找到对应学生信息");
        }
        
        // 构建查询参数
        java.util.Map<String, Object> params = new java.util.HashMap<>();
        params.put("studentId", student.getId());
        params.put("page", page);
        params.put("size", size);
        params.put("positionName", positionName);
        params.put("status", status);
        
        java.util.Map<String, Object> result = positionApplicationService.getMyApplications(params);
        return R.ok(result);
    }

    @GetMapping("/teacher-list")
    public R teacherList(@RequestHeader("Authorization") String token,
                        @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer size) {
        // 解析token获取userId
        String realToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Integer userId = null;
        try {
            io.jsonwebtoken.Claims claims = com.example.javaproject.util.JwtUtil.parseToken(realToken);
            Object idObj = claims.get("userId");
            if (idObj instanceof Integer) {
                userId = (Integer) idObj;
            } else if (idObj instanceof Number) {
                userId = ((Number) idObj).intValue();
            } else if (idObj != null) {
                userId = Integer.parseInt(idObj.toString());
            }
        } catch (Exception e) {
            return R.error("token无效或已过期");
        }
        if (userId == null) {
            return R.error("未登录或token无效");
        }
        // 通过 userId 查 teacherId
        com.example.javaproject.entity.Teacher teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("未找到对应教师信息");
        }
        java.util.Map<String, Object> params = new java.util.HashMap<>();
        params.put("teacherId", teacher.getId());
        params.put("page", page);
        params.put("size", size);
        java.util.Map<String, Object> result = positionApplicationService.getApplicationsByTeacherIdPaged(params);
        return R.ok(result);
    }

    @PostMapping("/approve")
    public R approve(@RequestBody java.util.Map<String, Object> body, @RequestHeader("Authorization") String token) {
        // 解析token校验
        String realToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        try {
            io.jsonwebtoken.Claims claims = com.example.javaproject.util.JwtUtil.parseToken(realToken);
        } catch (Exception e) {
            return R.error("token无效或已过期");
        }
        Integer id = null, status = null;
        String suggestion = null;
        try {
            id = Integer.parseInt(body.get("id").toString());
            status = Integer.parseInt(body.get("status").toString());
            if (body.get("suggestion") != null) {
                suggestion = body.get("suggestion").toString();
            }
        } catch (Exception e) {
            return R.error("参数错误");
        }
        PositionApplication app = positionApplicationService.getById(id);
        if (app == null) return R.error("申请不存在");
        app.setStatus(status);
        app.setUpdateTime(new java.util.Date());
        app.setSuggestion(suggestion);
        boolean ok = positionApplicationService.updateById(app);
        return ok ? R.ok(null) : R.error("审批失败");
    }
} 